package com.zoroki.hmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoroki.hmusic.entity.Favorite;
import com.zoroki.hmusic.entity.FavoriteSong;
import com.zoroki.hmusic.es.EsSongRepository;
import com.zoroki.hmusic.mapper.FavoriteSongMapper;
import com.zoroki.hmusic.service.IFavoriteService;
import com.zoroki.hmusic.service.IFavoriteSongService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@Service
@Slf4j
public class FavoriteSongServiceImpl extends ServiceImpl<FavoriteSongMapper, FavoriteSong> implements IFavoriteSongService {

    @Autowired
    private FavoriteSongMapper favoriteSongMapper;

    @Autowired
    private IFavoriteService favoriteService;

    @Autowired
    EsSongRepository esSongRepository;

    @Override
    public int deleteFavoriteSongByUserId(int userId,int songId) {
        //1.通过userId查询到favoriteId
        Favorite favorite = favoriteService.findFavoriteByUserId(userId);

        //2.通过favoriteId 和 songId 删除记录
        QueryWrapper<FavoriteSong> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_id", favorite.getId())
                .eq("song_id", songId);

        return favoriteSongMapper.delete(wrapper);
    }

    @Override
    public int deleteFavoriteSongBySongId(int songId) {
        QueryWrapper<FavoriteSong> wrapper = new QueryWrapper<>();
        wrapper.eq("song_id", songId);
        int delete = favoriteSongMapper.delete(wrapper);
        if (delete > 0) {
            log.info("favoriteSong成功");
            return 1;
        }
        log.error("favoriteSong删除失败");
        return 0;
    }

    @Override
    public int addSongToFavorite(FavoriteSong favoriteSong) {
        return favoriteSongMapper.insert(favoriteSong);
    }

    @Override
    public FavoriteSong checkSongIsFavorite(int favoriteId, int songId) {
        QueryWrapper<FavoriteSong> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_id", favoriteId)
                .eq("song_id", songId);
        return favoriteSongMapper.selectOne(wrapper);
    }
}
